<?php
/* $Id: production.php 20 2009-12-04 22:50:33Z ronan $ */
$basesite=$_SERVER['PHP_SELF'];
require("common.php");
require("auth.php");
RequireUserLevel(array('producer', 'producertrader', 'trader', 'headproducer', 'admin'));
require("header.php");
echo "<a href=\"production.php?f=viewyours\">Accepted Orders</a> | <a href=\"production.php?f=viewavailable\">All Available Orders</a> | <a href=\"production.php?f=viewavailable&usebps=1\">Buildable Available Orders</a> | <a href=\"production.php?f=viewavailable&usebps=-1\">Non-Buildable Available Orders</a> | <a href=\"production.php?f=blueprints\">Find Blueprints</a> | <a href=\"production.php?f=bplibrary\">Your Blueprints</a><br /><br />\n\n";
if(isset($_GET['f'])) $f=$_GET['f']; else if(isset($_POST['f'])) $f=$_POST['f'];
else { require("footer.php"); exit; }
if($f=="removebp") {
	$f='bplibrary';
	if(!isset($_GET['typeid'])) {
		echo "No id specified for removal!<br /><br />\n\n";
	} else {
		$typeID=$_GET['typeid'];
		$bp=Query("SELECT * FROM producerblueprints WHERE producerID=$uidnum AND typeID=$typeID LIMIT 1");
		if(mysql_num_rows($bp)==0) {
			echo "You don't have this blueprint in your library - it's already gone.<br /><br />\n\n";
		} else {
			$result=Query("DELETE FROM producerblueprints WHERE producerID=$uidnum AND typeID=$typeID LIMIT ".mysql_num_rows($bp));
			echo "Deleted the blueprint from your library.<br /><br />\n\n";
		}
	}
}
if($f=="bplibrary") {
	$items = getItemsByProducerId($uidnum);
	//Query("SELECT * FROM items WHERE typeID IN (SELECT `typeID` FROM producerblueprints WHERE producerID=$uidnum) ORDER BY typeName ASC");
	
	if(!mysql_num_rows($items)) {
		echo "We do not have a record of any of your blueprints. Add some in the browse window!<br />\n";
		require('footer.php');
		exit;	
	}
	$r='';
	$i=0;
	$r.= "<table border=0 cellspacing=0 cellpadding=2><tr><td></td><td><b>Name</b></td><td><b>Price</b></td><td><b>Availability</b></td><td><b>Options</b></td></tr>\n";
	while ($l = mysql_fetch_array($items, MYSQL_ASSOC)) {
		$typeID=$l['typeID'];
		$gfx=getGraphicPath($typeID);
		$imgsize=getImgsize($typeID);
		$r.=($bgcolored?"<tr class=\"itemtablecolor1\">":"<tr class=\"itemtablecolor2\">"); $bgcolored= !$bgcolored;
		$r .= 	"<!--ID: ".$l['typeID']."-->\t" .
			"<td width=\"$imgsize\"><img width=\"$imgsize\" height=\"$imgsize\" src=\"$gfx\" /></td>\t" .
			"<td width=\"150\">".($ingame?'<a href="showinfo:'.$l['typeID'].'">':'').$l['typeName'].($ingame?'</a>':'')."</td>\t";
		
		$r.="<td width=\"125\">".addCommas($l['price'])." per ".addCommas($l['quantityModifier'])."</td>\t"; 
		$r.="<td width=\"125\">";
		$r.= displayAvailability($l['numAvailable'],$l['isBuildable'],$l['isSpecialOrderable']);
		$r.="</td>\t";	

		$r.="<td width=\"175\"><a href=\"production.php?f=removebp&typeid=".$l['typeID']."\">Remove from library</a></td>";		
		$r .= "</tr>\n";
		$i++;
	}
	$r.="</table>\n";
	echo $r;
	require("footer.php");
	exit;
}
if($f=="cart") {
	$id=$_POST['id'];
	$qty = stripCommas($_POST['quantity']);
	$blueprint = Query("SELECT * FROM blueprints WHERE id='$id' LIMIT 1");
	$typeID=mysql_result($blueprint,0,'typeID');
	$item =  getItemById($typeID);
	$name=mysql_result($item, 0, 'typeName');
	$price=mysql_result($blueprint, 0, 'price');
	$numAvailable=mysql_result($blueprint, 0, 'numAvailable');
	$orders=Query("SELECT * FROM orders WHERE customerID=$uidnum AND status='in cart' AND usingStock=3");
	$q=0;
	if(!is_number($qty) || $qty<1 || $qty>$maxQuantity) {
		echo "ERROR: bad quantity!";
		require("footer.php");
		exit;
	}
	while($l=mysql_fetch_array($orders)) {
		if( $id==$l['typeID']) {
			$newqty = $qty+$l['quantity'];
			if($newqty>$maxQuantity) { echo "ERROR: Adding $qty of this item leaves your cart with more of this item than the allowable maximum. Not added."; require("footer.php"); exit; }
			if($newqty>$numAvailable) { echo "ERROR: Adding $qty of this blueprint leaves your cart with more of this blueprint than we have. Not added."; require("footer.php"); exit; }
			$results = Query("UPDATE orders SET quantity=quantity+".$qty.", priceTotal=pricePerUnit*quantity WHERE id='".$l['id']."' LIMIT 1");
			$q=1;
			break;
		}
	}
	if($qty > $numAvailable) {
		echo "We have $numAvailable \"$name\"s in stock, but you tried to order $qty.<br />\n";
		$qty = $numAvailable;
	}
	if(!$q) $results = Query("INSERT INTO orders (typeId, typeName, quantity, pricePerUnit, priceTotal, customerID, customerName, status, usingStock) VALUES('$id', '$name', '$qty', '$price', '".($price*$qty)."', '$uidnum', '$uid', 'in cart', '3')");
	echo "$qty \"$name\"".($qty==1?' has':'s have')." been added to the cart.<br />\n";
	echo "<br />\n";	
	$f="blueprints";
}
if($f=="blueprints") {
	$marketGroup= (isset($_GET['marketgroup'])?$_GET['marketgroup']:null);
	$hastypes=(isset($_GET['hastypes'])?$_GET['hastypes']:null);
	if(isset($marketGroup)&&$marketGroup=='all') echo "To go by category instead of seeing all available blueprints, <a href=\"".$_SERVER['PHP_SELF']."?f=blueprints\">click here</a>.<br /><br />\n\n";
	else echo "To see all available blueprints instead of going by category, <a href=\"".$_SERVER['PHP_SELF']."?f=blueprints&marketgroup=all&hastypes=1\">click here</a>.<br /><br />\n\n";
	echo getBlueprintMarketPath(isset($marketGroup)?$marketGroup:null) . "<br /><br />\n\n";
	echo getBlueprintMarketGroup(isset($marketGroup)?$marketGroup:null, isset($hastypes)?$hastypes:null);
	require("footer.php");
	exit;
}
if($f=="minerals") {
	if(isset($_GET['id'])) $id=$_GET['id'];
	else { echo "You don't have an order id to get mineral costs of!"; require("footer.php"); exit; }
	$order=Query("SELECT * FROM orders WHERE id='$id' LIMIT 1");
	$item=getItemById(mysql_result($order,0,'typeID'));
	$bp= searchItemsBySubString(mysql_result($item,0,'typeName')." Blueprint");
	$mc = getMineralCosts(mysql_result($bp,0,'typeID'), mysql_result($order,0,'quantity')*mysql_result($order,0,'quantityModifier'));
	echo "The base mineral requirements for ".mysql_result($order,0,'quantity')."x".mysql_result($order,0,'quantityModifier')." ".mysql_result($item,0,'typeName')."(s) are estimated as follows:<br /><br />\n\n";
	echo '<table border="0" cellspacing="0" cellpadding="3">';
	foreach($mc as $name=>$qty) {
		$mineral= getItemById($name);
		echo "<tr><td><img width=\"$imgsize\" height=\"$imgsize\" src=\"".getGraphicPath(mysql_result($mineral,0,'typeID'))."\" /></td>" .
				"<td>".mysql_result($mineral,0,'typeName')."</td>" .
				"<td>".number_format($qty, 2, ".", ",")."</td></tr>";
	}
	echo '</table>';
	require("footer.php");
	exit;
}
if($f=="accept") {
	//if(isset($_POST['id'])) $id=$_POST['id'];
	if(!empty($_POST['id']) && is_array($_POST['id'])) $id = $_POST['id'];
	else { echo "You don't have an order id to accept!"; require("footer.php"); exit; }
	$idlist = "";
	foreach($id as $idn) {
		$idlist .= (isset($andtemp)?' OR ':'') . 'id="'.$idn.'"';
		$andtemp=1;
	}
	unset($andtemp);
	$order=Query("SELECT * FROM orders WHERE $idlist LIMIT ".count($id));
	echo "You have chosen to accept the following order(s). Is this correct? <br /><br />\n\n";
	echo "<table border=0 cellspacing=0 cellpadding=2><tr><td><b>ID</b></td><td><b>Placed</b></td><td><b>Item</b></td><td><b>Qty</b></td><td><b>Total</b></td><td><b>Customer</b></td><td><b>Status</b></td><td></td><td></td></tr>\n";
	while($line=mysql_fetch_array($order)) {
		echo ($bgcolor?"<tr class=\"tablecolor1\">":"<tr class=\"tablecolor2\">");
		$bgcolor= !$bgcolor;
		echo
	    			"<td>".$line['id']."</td>\t" .
	    			"<td>".dateTime($dateTimeFormat,$line['timePlaced'])."</td>\t" .
	    			"<td>".$line['typeName']."</td>\t" .
	    			"<td>".addCommas($line['quantity']).($line['quantityModifier']==1?'':"x".addCommas($line['quantityModifier']))."</td>\t" .
	    			"<td>".addCommas($line['priceTotal'])." ISK</td>\t" .
	    			"<td>".evemail($line['customerName'])."</td>\t" .
	    			"<td>".ucwords($line['status'])."</td>\t" .
	    		"</tr>\n";
		/*echo "I would like to confirm, but I only want to accept " .
			"<form method=\"POST\" action=\"production.php\">".generateHiddenFields(array("id"=>$id, "oqty"=>$line['quantity'], "f"=>"acceptconfirmqty"))."<input type=\"text\" size=\"6\" name=\"qty\" value=\"1\" /> unit out of a possible " .
			addCommas($line['quantity'])." units. <input type=\"submit\" value=\"Confirm Partial Order\"></form>"; */
	}
	echo "</table><br /><br />\n\n".generateButton("Confirm", "POST", array("id"=>implode(';',$id), "f"=>"acceptconfirm"))." ".generateButton("Do not confirm", "GET", array("f"=>"viewavailable"))."<br /><br />\n\n";
	require("footer.php");
	exit;
}
if($f=="progress") {
	if(!empty($_POST['id']) && is_array($_POST['id'])) $id = $_POST['id'];
	else { echo "You don't have an order id to progress!"; require("footer.php"); exit; }		$contractlist = array();	$counter=0;
	$idlist = "";
	foreach($id as $idn) {
		$idlist .= (isset($andtemp)?' OR ':'') . 'id="'.$idn.'"';
		$andtemp=1;
	}
	unset($andtemp);
	$order=Query("SELECT * FROM orders WHERE $idlist LIMIT ".count($id));
	echo "You have chosen to progress the following order(s). Is this correct? <br /><br />\n\n";
	echo "<table border=0 cellspacing=0 cellpadding=2><tr><td><b>ID</b></td><td><b>Placed</b></td><td><b>Item</b></td><td><b>Qty</b></td><td><b>Total</b></td><td><b>Customer</b></td><td><b>Status</b></td><td></td><td></td></tr>\n";
	while($line=mysql_fetch_array($order)) {
		echo ($bgcolor?"<tr class=\"tablecolor1\">":"<tr class=\"tablecolor2\">");
		$bgcolor= !$bgcolor;
		echo 
	 		"<td>".$line['id']."</td>\t" .
	 		"<td>".dateTime($dateTimeFormat,$line['timePlaced'])."</td>\t" .
	 		"<td>".$line['typeName']."</td>\t" .
			"<td>".addCommas($line['quantity']).($line['quantityModifier']==1?'':"x".addCommas($line['quantityModifier']))."</td>\t" .
	    	"<td>".addCommas($line['priceTotal'])." ISK</td>\t" .
	    	"<td>".evemail($line['customerName'])."</td>\t" .
	    	"<td>".ucwords($line['status'])." <font color=\"red\">BECOMES</font> ".ucwords(nextStage($line['status']))."</td>\t";
	    	"</tr>\n";
		if(nextStage($line['status'])=='on contract') {
			if(array_key_exists($line['customerName'], $contractlist))
				$contractlist[$line['customerName']] .= ",".$counter;
			else
				$contractlist[$line['customerName']] = $counter;
		}
		$counter++;
	}
	echo "</table>\n";
	if(!empty($contractlist)) {
		echo "<br />\n";
		foreach($contractlist as $customerName=>$rowlist) {
			$msgbody = "";
			$total=0;
			$rows = explode(",",$rowlist);
			foreach($rows as $row) {
				$total += mysql_result($order, $row, 'priceTotal');
				$msgbody .= "On Contract: ".addCommas(mysql_result($order, $row, 'quantity'))."x".addCommas(mysql_result($order, $row, 'quantityModifier'))." of ".mysql_result($order, $row, 'typeName')." for ".addCommas(mysql_result($order, $row, 'priceTotal'))."ISK\n";
			}
			$msgbody .= "\n\n Total: ".addCommas($total)." ISK (".addCommas($total+10000)." ISK with contract fee)";
			echo "<br />\n";
			echo "You are advancing one or more of $customerName's orders to \"On Contract\" status! " .
			"<font color=\"green\">The total price of the contract(s) comes to <b>".addCommas($total)."</b> ISK.</font> " .
			"<font color=\"yellow\">Before you confirm this, please ".evemail(
				$customerName,
 				"TGRAD Order Tool: Contract Alert",
 				$msgbody,
				"evemail the customer"
			)."! <A href=\"javascript: alert('$msgbody')\">Click here!</A></font>";
			if(!$ingame) echo "<font color=\"red\"> WARNING: You are not in game. Please use the IGB for this step so you can send the customer an evemail and put the item(s) on contract.</font>\n";
			echo "</td></tr>";
		}
	}
	echo "<br /><br />\n\n".generateButton("Confirm", "POST", array("id"=>implode(';',$id), "f"=>"progressconfirm"))." ".generateButton("Do not confirm", "GET", array("f"=>"viewyours"));
	require("footer.php");
	exit;
}

if($f=="regress") {
	if(!empty($_POST['id']) && is_array($_POST['id'])) $id = $_POST['id'];
	else { echo "You don't have an order id to regress!"; require("footer.php"); exit; }
	$contractlist = array();
	$counter=0;
	$idlist = "";
	foreach($id as $idn) {
		$idlist .= (isset($andtemp)?' OR ':'') . 'id="'.$idn.'"';
		$andtemp=1;
	}
	unset($andtemp);
	$order=Query("SELECT * FROM orders WHERE $idlist LIMIT ".count($id));
	echo "You have chosen to <font color=\"red\"><b>REGRESS</b></font> the following order(s). Is this correct? <br /><br />\n\n";
	echo "<table border=0 cellspacing=0 cellpadding=2><tr><td><b>ID</b></td><td><b>Placed</b></td><td><b>Item</b></td><td><b>Qty</b></td><td><b>Total</b></td><td><b>Customer</b></td><td><b>Status</b></td><td></td><td></td></tr>\n";
	while($line=mysql_fetch_array($order)) {
		echo ($bgcolor?"<tr class=\"tablecolor1\">":"<tr class=\"tablecolor2\">");
		$bgcolor= !$bgcolor;
		echo 
	 		"<td>".$line['id']."</td>\t" .
	 		"<td>".dateTime($dateTimeFormat,$line['timePlaced'])."</td>\t" .
	 		"<td>".$line['typeName']."</td>\t" .
			"<td>".addCommas($line['quantity']).($line['quantityModifier']==1?'':"x".addCommas($line['quantityModifier']))."</td>\t" .
	    	"<td>".addCommas($line['priceTotal'])." ISK</td>\t" .
	    	"<td>".evemail($line['customerName'])."</td>\t" .
	    	"<td>".ucwords($line['status'])." <font color=\"red\">BECOMES</font> ".ucwords(prevStage($line['status']))."</td>\t";
	    	"</tr>\n";
		$counter++;
	}
	echo "</table>\n";
	echo "<br /><br />\n\n<font color=\"red\">DOUBLE CHECK THESE BEFORE CONFIRMING. You are <b><u>REGRESSING</u></b> orders.</font><br /><br />\n\n".generateButton("Confirm", "POST", array("id"=>implode(';',$id), "f"=>"regressconfirm"))." ".generateButton("Do not confirm", "GET", array("f"=>"viewyours"));
	require("footer.php");
	exit;
}
if($f=="withdraw") {
	if(!empty($_POST['id']) && is_array($_POST['id'])) $id = $_POST['id'];
	else { echo "You don't have an order id to withdraw from!"; require("footer.php"); exit; }
	$idlist = "";
	foreach($id as $idn) {
		$idlist .= (isset($andtemp)?' OR ':'') . 'id="'.$idn.'"';
		$andtemp=1;
	}
	unset($andtemp);
	$order=Query("SELECT * FROM orders WHERE $idlist LIMIT ".count($id));
		echo "<font color=\"red\">You have chosen to withdraw from the following order(s).<br />\n" .
			"The order will be reset to \"Awaiting Producer\" status, and the customer(s) will be sad.<br />\n" .
			"Is this correct?</font><br /><br />\n\n";
	echo "<table border=0 cellspacing=0 cellpadding=2><tr><td><b>ID</b></td><td><b>Placed</b></td><td><b>Item</b></td><td><b>Qty</b></td><td><b>Total</b></td><td><b>Customer</b></td><td><b>Status</b></td><td></td><td></td></tr>\n";
	while($line=mysql_fetch_array($order)) {
		echo ($bgcolor?"<tr class=\"tablecolor1\">":"<tr class=\"tablecolor2\">");
		$bgcolor= !$bgcolor;
		echo
	    			"<td>".$line['id']."</td>\t" .
	    			"<td>".dateTime($dateTimeFormat,$line['timePlaced'])."</td>\t" .
	    			"<td>".$line['typeName']."</td>\t" .
	    			"<td>".addCommas($line['quantity']).($line['quantityModifier']==1?'':"x".addCommas($line['quantityModifier']))."</td>\t" .
	    			"<td>".addCommas($line['priceTotal'])." ISK</td>\t" .
	    			"<td>".evemail($line['customerName'])."</td>\t" .
	    			"<td>".ucwords($line['status'])."</td>\t" .
	    		"</tr>\n";
	}
	echo "</table>";
	echo "<br /><br />\n\n".generateButton("Confirm", "POST", array("id"=>implode(';',$id), "f"=>"withdrawconfirm"))." ".generateButton("Do not confirm", "GET", array("f"=>"viewyours"));
	require("footer.php");
	exit;
}
if($f=="acceptconfirmqty") {
	if(isset($_POST['id'])) $id=$_POST['id'];
	else { echo "You don't have an order id to accept!"; require("footer.php"); exit; }
	if(isset($_POST['qty'])) $qty=stripCommas($_POST['qty']);
	else { echo "You don't have a quantity to accept!"; require("footer.php"); exit; }
	$origorder = mysql_fetch_array(Query("SELECT * FROM orders WHERE id=$id LIMIT 1"));
	$oqty=$origorder['quantity'];
	if(!is_number($qty) || $qty<1 || $qty>$oqty) {	echo "Error: You have specified an invalid quantity. Specify an integer greater than 0 and at most $oqty."; require("footer.php"); exit; }
	if($qty==$oqty) {
		$f="acceptconfirm";
	} else {
		$fields=array();
		$dqueryr=Query("DESC orders");
		while($line = mysql_fetch_array($dqueryr)) {
			array_push($fields, $line['Field']);
		}	
		$ks=$vs='';
		foreach($fields as $f) {
			if($f=='id' || $f=='producerName' || $f=='timeCompleted') continue;
			$v=$origorder[$f];
			if(isset($commatemp)) {$ks.=', '; $vs.=', ';} else $commatemp=true;
			if($f=='quantity') $v=$oqty-$qty;
			if($f=='priceTotal') $v=($origorder['pricePerUnit']*($oqty-$qty));
			$ks.=$f; $vs.="'$v'";
		}
		$resultsInsert = Query("INSERT INTO orders($ks) VALUES($vs)");
		$resultsUpdate = Query("UPDATE orders SET producerID='$uidnum', producerName='$uid', priceTotal='".($origorder['pricePerUnit']*$qty)."', status='in queue', quantity='$qty' WHERE id=$id LIMIT 1");
		echo "You have accepted the order. ($qty/$oqty)<br /><br />\n\n";
		$f="viewyours";
		unset($id);
	}
}
if($f=="acceptconfirm") {
	if(!empty($_POST['id'])) $id = explode(';',$_POST['id']);
	else { echo "You don't have an order id to accept!"; require("footer.php"); exit; }
	$idlist = "";
	foreach($id as $idn) {
		$idlist .= (isset($andtemp)?' OR ':'') . 'id="'.$idn.'"';
		$andtemp=1;
	}
	unset($andtemp);
	$order=Query("SELECT * FROM orders WHERE $idlist LIMIT ".count($id));
	while($line=mysql_fetch_array($order))
		$results = Query("UPDATE orders SET producerID='$uidnum', producerName='$uid', status='".nextStage($line['status'])."' WHERE id='".$line['id']."' LIMIT 1");
	echo "You have accepted ".mysql_num_rows($order)." order(s).<br /><br />\n\n";
	$f="viewyours";
	unset($id);
}
if($f=="regressconfirm") {
	if(!empty($_POST['id'])) $id = explode(';',$_POST['id']);
	else { echo "You don't have an order id to regress!"; require("footer.php"); exit; }
	$idlist = "";
	foreach($id as $idn) {
		$idlist .= (isset($andtemp)?' OR ':'') . 'id="'.$idn.'"';
		$andtemp=1;
	}
	unset($andtemp);
	$order=Query("SELECT * FROM orders WHERE $idlist LIMIT ".count($id));
	while($line=mysql_fetch_array($order)) { 
		$prev=prevStage($line['status']);
		if($prev=='awaiting producer') {
			$results = Query("UPDATE orders SET status='$prev', producerID=NULL, producerName=NULL WHERE id=".$line['id']." LIMIT 1");
		} else {
			$results = Query("UPDATE orders SET status='$prev' WHERE id=".$line['id']." LIMIT 1");	
		}
		echo "You have regressed an order to \"".ucwords($prev)."\".<br /><br />\n\n";
	}
	$f="viewyours";
	unset($id);
}
if($f=="progressconfirm") {
	if(!empty($_POST['id'])) $id = explode(';',$_POST['id']);
	else { echo "You don't have an order id to progress!"; require("footer.php"); exit; }
	$idlist = "";
	foreach($id as $idn) {
		$idlist .= (isset($andtemp)?' OR ':'') . 'id="'.$idn.'"';
		$andtemp=1;
	}
	unset($andtemp);
	$order=Query("SELECT * FROM orders WHERE $idlist LIMIT ".count($id));
	while($line=mysql_fetch_array($order)) { 
		$next=nextStage($line['status']);
		if($next=='completed') {
			$results = Query("UPDATE orders SET status='$next', timeCompleted=NOW() WHERE id=".$line['id']." LIMIT 1");
		} else {
			$results = Query("UPDATE orders SET status='$next' WHERE id=".$line['id']." LIMIT 1");	
		}
		echo "You have progressed an order to \"".ucwords($next)."\".<br /><br />\n\n";
	}
	$f="viewyours";
	unset($id);
}
if($f=="withdrawconfirm") {
	if(!empty($_POST['id'])) $id = explode(';',$_POST['id']);
	else { echo "You don't have an order id to progress!"; require("footer.php"); exit; }
	$idlist = "";
	foreach($id as $idn) {
		$idlist .= (isset($andtemp)?' OR ':'') . 'id="'.$idn.'"';
		$andtemp=1;
	}
	unset($andtemp);
	$orderlist=Query("SELECT * FROM orders WHERE $idlist LIMIT ".count($id));
	while($line=mysql_fetch_array($orderlist)) { 
		$status='awaiting producer';
		if($line['usingStock']>=1) $status='awaiting processing';
		$results = Query("UPDATE orders SET producerID=NULL, producerName=NULL, status='$status' WHERE id=".$line['id']." LIMIT 1");
		$orders=Query("SELECT * FROM orders WHERE id<>'".$line['id']."' AND typeID='".$line['typeID']."' AND timePlaced='".$line['timePlaced']."' AND usingStock='".$line['usingStock']."'");
		while($l=mysql_fetch_array($orders)) {
			if(combineOrders($l['id'], $line['id'])) break;
		}	
	}
	echo "You have withdrawn from ".mysql_num_rows($orderlist)." order(s).<br /><br />\n\n";
	$f="viewyours";
	unset($id);
}
if($f=="viewyours") {
	$orderby=(isset($_GET['orderby'])?$_GET['orderby']:'timePlaced');
	$ad=(isset($_GET['ad'])?$_GET['ad']:'ASC');
	//$start=(isset($_GET['start'])?$_GET['start']:0);
	//$perPage=(isset($_GET['perpage'])?$_GET['perpage']:30);
	$orders = Query("SELECT * FROM orders WHERE producerID='$uidnum' AND status <> 'completed' ORDER BY $orderby $ad, typeName ASC");
	echo "<br /><br />\n\n<h3>Outstanding Orders</h3><br />\n";
	if(!mysql_num_rows($orders)) {
		echo "You do not have any outstanding orders.<br /><br />";
	} else {
		echo "<form method=\"POST\" action=\"production.php\"><table border=0 cellspacing=0 cellpadding=2>" .
		"<tr>" .
		"<td><b><a href=\"production.php?f=viewyours&orderby=id&ad=".($orderby=='id'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">ID</a></b></td>" .
		"<td><b><a href=\"production.php?f=viewyours&orderby=timePlaced&ad=".($orderby=='timePlaced'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">Placed</a></b></td>" .
		"<td><b><a href=\"production.php?f=viewyours&orderby=typeName&ad=".($orderby=='typeName'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">Item</a></b></td>" .
		"<td><b><a href=\"production.php?f=viewyours&orderby=quantity&ad=".($orderby=='quantity'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">Qty</a></b></td>" .
		"<td><b><a href=\"production.php?f=viewyours&orderby=priceTotal&ad=".($orderby=='priceTotal'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">Total</a></b></td>" .
		"<td><b><a href=\"production.php?f=viewyours&orderby=customerName&ad=".($orderby=='customerName'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">Customer</a></b></td>" .
		"<td><b><a href=\"production.php?f=viewyours&orderby=usingStock&ad=".($orderby=='usingStock'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">Type</a></b></td>" .
		"<td><b><a href=\"production.php?f=viewyours&orderby=status&ad=".($orderby=='status'?($ad=='DESC'?'ASC':'DESC'):'ASC')."\">Status</a></b></td>" .
		"<td></td>" .
		"</tr>\n";
		while ($line = mysql_fetch_array($orders, MYSQL_ASSOC)) {
			echo ($bgcolor?"<tr class=\"tablecolor1\">":"<tr class=\"tablecolor2\">");
			$bgcolor= !$bgcolor;
			echo "\t" .
	    			"<td>".$line['id']."</td>\t" .
	    			"<td>".dateTime($dateTimeFormat,$line['timePlaced'])."</td>\t" .
	    			"<td>".$line['typeName']."</td>\t" .
	    			"<td>".addCommas($line['quantity']).($line['quantityModifier']==1?'':"x".addCommas($line['quantityModifier']))."</td>\t" .
	    			"<td>".addCommas($line['priceTotal'])." ISK</td>\t" .
	    			"<td>".evemail($line['customerName'])."</td>\t" .
	    			"<td>".getColoredType($line['usingStock'])."</td>\t" .
	    			"<td>".ucwords($line['status'])."</td>\t" .
	    			//"<td>".generateButton("To ".ucwords(nextStage($line['status'])),"POST",array("f"=>"progress", "id"=>$line['id']))."</td>\t" .
	    			//"<td>".($line['status']=='on contract'?'':generateButton("Withdraw","POST",array("f"=>"withdraw", "id"=>$line['id'])))."</td>\t" .
	    			"<td><input type=\"checkbox\" name=\"id[]\" value=\"".$line['id']."\" /></td>\t" .
	    			"</tr>\n";
		}
		echo "</table><input type=\"submit\" name=\"f\" value=\"progress\" /> checked orders<br />\n" .
				"<input type=\"submit\" name=\"f\" value=\"regress\" /> checked orders<br />\n" .
				"<input type=\"submit\" name=\"f\" value=\"withdraw\" /> from checked orders<br /><br />";
	}
	$orders = Query("SELECT * FROM orders WHERE producerID='$uidnum' AND status='completed' ORDER BY timeCompleted DESC LIMIT 10");
	echo "<br /><br />\n\n<h3>Completed Orders</h3><br />\n";
	if(!mysql_num_rows($orders)) {
		echo "You have not completed any orders.";
		require("footer.php");
		exit;
	}
	$bgcolor=false;
	echo "<table border=0 cellspacing=0 cellpadding=2><tr><td><b>ID</b></td><td><b>Placed</b></td><td><b>Completed</b></td><td><b>Item</b></td><td><b>Qty</b></td><td><b>Total</b></td><td><b>Customer</b></td><td>Type</td></tr>\n";
	while ($line = mysql_fetch_array($orders, MYSQL_ASSOC)) {
		echo ($bgcolor?"<tr class=\"tablecolor1\">":"<tr class=\"tablecolor2\">");
		$bgcolor= !$bgcolor;
		echo "\t" .
			"<td>".$line['id']."</td>\t" .
    		"<td>".dateTime($dateTimeFormat,$line['timePlaced'])."</td>\t" .
    		"<td>".dateTime($dateTimeFormat,$line['timeCompleted'])."</td>\t" .
    		"<td>".$line['typeName']."</td>\t" .
    		"<td>".addCommas($line['quantity']).($line['quantityModifier']==1?'':"x".addCommas($line['quantityModifier']))."</td>\t" .
    		"<td>".addCommas($line['priceTotal'])." ISK</td>\t" .
    		"<td>".evemail($line['customerName'])."</td>\t" .
    		"<td>".getColoredType($line['usingStock'])."</td>\t" .
   			"</tr>\n";
	}
	echo "</table>";
	require("footer.php");
	exit;
}
if($f=="viewavailable") {
	$porderby=(isset($_GET['porderby'])?$_GET['porderby']:'timePlaced');
	$pad=(isset($_GET['pad'])?$_GET['pad']:'ASC');
	$torderby=(isset($_GET['torderby'])?$_GET['torderby']:'timePlaced');
	$tad=(isset($_GET['tad'])?$_GET['tad']:'ASC');
	if($userLevel=='producer'||$userLevel=='producertrader'||$userLevel=='headproducer'||$userLevel=='admin') {
		$usingBPs=(isset($_GET['usebps'])?$_GET['usebps']:0);
		if($usingBPs==1) {
			echo "<h3>Available Production Orders Which You Can Build</h3><br /><br />\n\n";
			$orders = Query("SELECT * FROM orders WHERE status='awaiting producer' AND typeID IN (SELECT `typeID` FROM producerblueprints WHERE producerID=$uidnum) ORDER BY $porderby $pad, typeName ASC");
		} else if($usingBPs==-1) {
			echo "<h3>Available Production Orders Which You CanNOT Build</h3><br /><br />\n\n";
			$orders = Query("SELECT * FROM orders WHERE status='awaiting producer' AND typeID <> ALL (SELECT `typeID` FROM producerblueprints WHERE producerID=$uidnum) ORDER BY $porderby $pad, typeName ASC");
		} else {
			echo "<h3>All Available Production Orders</h3><br /><br />\n\n";
			$orders = Query("SELECT * FROM orders WHERE status='awaiting producer' ORDER BY $porderby $pad, typeName ASC");
		}
		
		if(!mysql_num_rows($orders)) {
			echo "There are no available production orders.";
		} else {
			echo "<form method=\"POST\" action=\"production.php\"><table border=0 cellspacing=0 cellpadding=2>" .
			"<tr>" .
			"<td><b><a href=\"production.php?f=viewavailable&torderby=$torderby&tad=$tad&porderby=id&pad=".($porderby=='id'?($pad=='DESC'?'ASC':'DESC'):'ASC')."\">ID</a></b></td>" .
			"<td><b><a href=\"production.php?f=viewavailable&torderby=$torderby&tad=$tad&porderby=timePlaced&pad=".($porderby=='timePlaced'?($pad=='DESC'?'ASC':'DESC'):'ASC')."\">Placed</a></b></td>" .
			"<td><b><a href=\"production.php?f=viewavailable&torderby=$torderby&tad=$tad&porderby=typeName&pad=".($porderby=='typeName'?($pad=='DESC'?'ASC':'DESC'):'ASC')."\">Item</a></b></td>" .
			"<td><b><a href=\"production.php?f=viewavailable&torderby=$torderby&tad=$tad&porderby=quantity&pad=".($porderby=='quantity'?($pad=='DESC'?'ASC':'DESC'):'ASC')."\">Qty</a></b></td>" .
			"<td><b><a href=\"production.php?f=viewavailable&torderby=$torderby&tad=$tad&porderby=priceTotal&pad=".($porderby=='priceTotal'?($pad=='DESC'?'ASC':'DESC'):'ASC')."\">Total</a></b></td>" .
			"<td><b><a href=\"production.php?f=viewavailable&torderby=$torderby&tad=$tad&porderby=customerName&pad=".($porderby=='customerName'?($pad=='DESC'?'ASC':'DESC'):'ASC')."\">Customer</a></b></td>" .
			"<td></td>" .
			"<td></td>" .
			"</tr>\n";
			while ($line = mysql_fetch_array($orders, MYSQL_ASSOC)) {
				echo ($bgcolor?"<tr class=\"tablecolor1\">":"<tr class=\"tablecolor2\">");
				$bgcolor= !$bgcolor;
				echo "\t" .
	    				"<td>".$line['id']."</td>\t" .
	    				"<td>".dateTime($dateTimeFormat,$line['timePlaced'])."</td>\t" .
	    				"<td>".$line['typeName']."</td>\t" .
	    				"<td>".addCommas($line['quantity']).($line['quantityModifier']==1?'':"x".addCommas($line['quantityModifier']))."</td>\t" .	    		
						"<td>".addCommas($line['priceTotal'])."</td>\t" .
	    				"<td>".evemail($line['customerName'])."</td>\t" .
	    				"<td><a href=\"production.php?f=minerals&id=".$line['id']."\">Minerals</a></td>" .
	    				//"<td>".generateButton("Accept", "POST", array("f"=>"accept", "id"=>$line['id']))."</td>\t" .
	    				"<td><input type=\"checkbox\" name=\"id[]\" value=\"".$line['id']."\" /></td>\t" .
		    			"</tr>\n";
			}
			echo "</table>".generateHiddenFields(array("f"=>"accept"))."<input type=\"submit\" value=\"Accept Checked Orders\" /></form>";
		}
	}
	if($userLevel=='trader'||$userLevel=='producertrader'||$userLevel=='headproducer'||$userLevel=='admin') {
		$bgcolor=false;
		if($userHasLevel['producer']) echo "<br /><br />\n\n";		
		echo "<h3>Available Trade Orders</h3><br /><br />\n\n";	
		$orders = Query("SELECT * FROM orders WHERE status='awaiting processing' ORDER BY $torderby $tad");
		if(!mysql_num_rows($orders)) {
			echo "There are no available trade orders.";
			require("footer.php");
			exit;
		}
		echo "<form method=\"POST\" action=\"production.php\"><table border=0 cellspacing=0 cellpadding=2>" .
		"<tr>" .
		"<td><b><a href=\"production.php?f=viewavailable&porderby=$porderby&pad=$pad&torderby=id&tad=".($torderby=='id'?($tad=='DESC'?'ASC':'DESC'):'ASC')."\">ID</a></b></td>" .
		"<td><b><a href=\"production.php?f=viewavailable&porderby=$porderby&pad=$pad&torderby=timePlaced&tad=".($torderby=='timePlaced'?($tad=='DESC'?'ASC':'DESC'):'ASC')."\">Placed</a></b></td>" .
		"<td><b><a href=\"production.php?f=viewavailable&porderby=$porderby&pad=$pad&torderby=typeName&tad=".($torderby=='typeName'?($tad=='DESC'?'ASC':'DESC'):'ASC')."\">Item</a></b></td>" .
		"<td><b><a href=\"production.php?f=viewavailable&porderby=$porderby&pad=$pad&torderby=quantity&tad=".($torderby=='quantity'?($tad=='DESC'?'ASC':'DESC'):'ASC')."\">Qty</a></b></td>" .
		"<td><b><a href=\"production.php?f=viewavailable&porderby=$porderby&pad=$pad&torderby=priceTotal&tad=".($torderby=='priceTotal'?($tad=='DESC'?'ASC':'DESC'):'ASC')."\">Total</a></b></td>" .
		"<td><b><a href=\"production.php?f=viewavailable&porderby=$porderby&pad=$pad&torderby=customerName&tad=".($torderby=='customerName'?($tad=='DESC'?'ASC':'DESC'):'ASC')."\">Customer</a></b></td>" .
		"<td><b><a href=\"production.php?f=viewavailable&porderby=$porderby&pad=$pad&torderby=usingStock&tad=".($torderby=='usingStock'?($tad=='DESC'?'ASC':'DESC'):'ASC')."\">Type</a></b></td>" .
		"<td></td>" .
		"<td></td>" .
		"</tr>\n";
		
		while ($line = mysql_fetch_array($orders, MYSQL_ASSOC)) {
			echo ($bgcolor?"<tr class=\"tablecolor1\">":"<tr class=\"tablecolor2\">");
			$bgcolor= !$bgcolor;
			echo "\t" .
	    			"<td>".$line['id']."</td>\t" .
	    			"<td>".dateTime($dateTimeFormat,$line['timePlaced'])."</td>\t" .
	    			"<td>".$line['typeName']."</td>\t" .
	    			"<td>".addCommas($line['quantity']).($line['quantityModifier']==1?'':"x".addCommas($line['quantityModifier']))."</td>\t" .	    		
					"<td>".addCommas($line['priceTotal'])."</td>\t" .
	    			"<td>".evemail($line['customerName'])."</td>\t" .
	    			"<td>".getColoredType($line['usingStock'])."</td>\t" .
	    			//"<td>".generateButton("Accept", "POST", array("f"=>"accept", "id"=>$line['id']))."</td>\t" .
	    			"<td><input type=\"checkbox\" name=\"id[]\" value=\"".$line['id']."\" /></td>\t" .
	    			"</tr>\n";
		}
		echo "</table>".generateHiddenFields(array("f"=>"accept"))."<input type=\"submit\" value=\"Accept Checked Orders\" /></form>";
	}	
}
require("footer.php");
?>
